package com.dsunsoft.rtu.task;

import com.dsunsoft.rtu.entity.HeartbeatInfo;
import com.dsunsoft.rtu.entity.RtuDevice;
import com.dsunsoft.rtu.netty.NettyHeartbeatMap;
import com.dsunsoft.rtu.query.RtuDeviceQuery;
import com.dsunsoft.rtu.service.RtuDeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class RtuDeviceOnlineTask {

    @Autowired
    private RtuDeviceService rtuDeviceService;

    /**
     * 同步设备在线状态
     */
    @Scheduled(cron = "0 */2 * * * ?")
    private void syncDeviceOnlineStatus() {
        try {
            // 当前时间
            long timeMillis = System.currentTimeMillis();
            // 获取所有设备
            List<String> deviceList = rtuDeviceService.getDeviceIdList();
            for (String deviceId : deviceList) {
                int onlineStatus = 0;
                HeartbeatInfo heartbeatInfo = NettyHeartbeatMap.get(Integer.parseInt(deviceId));
                if (heartbeatInfo != null) {
                    // 距离当前时间30分钟视为离线
                    long diffMinute = (timeMillis - heartbeatInfo.getLastReportDate().getTime()) / (1000 * 60);
                    if (diffMinute < 60) {
                        onlineStatus = 1;
                    }
                }
                rtuDeviceService.updateOnlineStatus(deviceId, onlineStatus);
            }

        } catch (Exception e) {
            log.error("同步设备在线状态出错: ", e);
        }

    }
}
